package com.buanalintas.sandals.pos.purchaseorder;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.sandals.pos.entities.PosTransactionPurchaseOrder;
import com.buanalintas.sandals.pos.entities.PosTransactionPurchaseOrderDetail;
import com.buanalintas.sandals.pos.purchaseorderdetail.PurchaseOrderDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PurchaseOrder extends Page {

    private Field purchaseOrderId;
    private Field purchaseOrderUserId;
    private Field purchaseOrderUnitId;
    private Field purchaseOrderSupplierId;
    private Field purchaseOrderNumber;
    private Field purchaseOrderStatus;
    private Field purchaseOrderKeel;
    private Field purchaseOrderDate;
    private Field purchaseOrderDescription;
    private Field purchaseOrderTimestamp;
    private Field purchaseOrderTotalQuantity;
    private Field purchaseOrderTotal;
    private Field purchaseOrderPaid;
    private Field purchaseOrderReturQuantity;
    private Field purchaseOrderReturTotal;
    private Field purchaseOrderReceived;
    private Field purchaseOrderProgress;

    public PurchaseOrder() {
        super();
        setTheClass(PosTransactionPurchaseOrder.class);
        setPageDetail(PurchaseOrderDetail.class);

        purchaseOrderId = new Field();
        purchaseOrderId.setName("purchaseOrderId");
        purchaseOrderId.setCaption("id");
        purchaseOrderId.setListProperties("");
        purchaseOrderId.setInputProperties("");
        getFields().add(purchaseOrderId);

        purchaseOrderNumber = new Field();
        purchaseOrderNumber.setName("purchaseOrderNumber");
        purchaseOrderNumber.setCaption("number");
        purchaseOrderNumber.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderNumber.setInputProperties(" size=\"20\" readonly");
        purchaseOrderNumber.setRequired(true);
        getFields().add(purchaseOrderNumber);

        purchaseOrderUnitId = new Field();
        purchaseOrderUnitId.setName("purchaseOrderUnitId");
        purchaseOrderUnitId.setCaption("unit");
        purchaseOrderUnitId.setListProperties("");
        purchaseOrderUnitId.setInputProperties("");
        getFields().add(purchaseOrderUnitId);

        purchaseOrderUserId = new Field();
        purchaseOrderUserId.setName("purchaseOrderUserId");
        purchaseOrderUserId.setCaption("user");
        purchaseOrderUserId.setListProperties("");
        purchaseOrderUserId.setInputProperties("");
        getFields().add(purchaseOrderUserId);

        purchaseOrderSupplierId = new Field();
        purchaseOrderSupplierId.setName("purchaseOrderSupplierId");
        purchaseOrderSupplierId.setCaption("supplier");
        purchaseOrderSupplierId.setListProperties(" width=\"10%\" nowrap");
        purchaseOrderSupplierId.setInputProperties(" size=\"30\" ");
        purchaseOrderSupplierId.setRequired(true);
//        purchaseOrderSupplierModelId.getSelectorAction().add(new String[]{"value", "returPurchaseOrderId", "PurchaseOrderId"});
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierCode", " Code", "width=\"30%\" nowrap"});
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierName", " Name", "width=\"50%\""});
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierPhone", " Phone", "align=\"center\" width=\"20%\" nowrap"});
        getFields().add(purchaseOrderSupplierId);

        purchaseOrderDate = new Field();
        purchaseOrderDate.setName("purchaseOrderDate");
        purchaseOrderDate.setCaption("date");
        purchaseOrderDate.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderDate.setInputProperties(" size=\"8\" readonly");
        purchaseOrderDate.setDefaultValue(Utility.getTimestamp());
        purchaseOrderDate.setRequired(true);
        getFields().add(purchaseOrderDate);

        purchaseOrderStatus = new Field();
        purchaseOrderStatus.setName("purchaseOrderStatus");
        purchaseOrderStatus.setCaption("status");
        purchaseOrderStatus.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderStatus.setInputProperties("");
        purchaseOrderStatus.getOptions().add(new String[]{"1", " NEW"});
        purchaseOrderStatus.getOptions().add(new String[]{"2", " RECEIPT"});
        getFields().add(purchaseOrderStatus);
        
        purchaseOrderKeel = new Field();
        purchaseOrderKeel.setName("purchaseOrderKeel");
        purchaseOrderKeel.setCaption("keel");
        purchaseOrderKeel.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderKeel.setInputProperties("");
        purchaseOrderKeel.getOptions().add(new String[]{"1", " No"});
        purchaseOrderKeel.getOptions().add(new String[]{"2", " Yes"});
        getFields().add(purchaseOrderKeel);

        purchaseOrderTotalQuantity = new Field();
        purchaseOrderTotalQuantity.setName("purchaseOrderTotalQuantity");
        purchaseOrderTotalQuantity.setCaption("quantity");
        purchaseOrderTotalQuantity.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        purchaseOrderTotalQuantity.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderTotalQuantity);
        
        purchaseOrderTotal = new Field();
        purchaseOrderTotal.setName("purchaseOrderTotal");
        purchaseOrderTotal.setCaption("total");
        purchaseOrderTotal.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        purchaseOrderTotal.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderTotal);
        
        purchaseOrderPaid = new Field();
        purchaseOrderPaid.setName("purchaseOrderPaid");
        purchaseOrderPaid.setCaption("paid");
        purchaseOrderPaid.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        purchaseOrderPaid.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderPaid);
        
        purchaseOrderReturQuantity = new Field();
        purchaseOrderReturQuantity.setName("purchaseOrderReturQuantity");
        purchaseOrderReturQuantity.setCaption("retur quantity");
        purchaseOrderReturQuantity.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        purchaseOrderReturQuantity.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderReturQuantity);
        
        purchaseOrderReturTotal = new Field();
        purchaseOrderReturTotal.setName("purchaseOrderReturTotal");
        purchaseOrderReturTotal.setCaption("retur total");
        purchaseOrderReturTotal.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        purchaseOrderReturTotal.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderReturTotal);

        purchaseOrderReceived = new Field();
        purchaseOrderReceived.setName("purchaseOrderReceived");
        purchaseOrderReceived.setCaption("received");
        purchaseOrderReceived.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        purchaseOrderReceived.setInputProperties(" size=\"8\"");
        getFields().add(purchaseOrderReceived);

        purchaseOrderProgress = new Field();
        purchaseOrderProgress.setName("purchaseOrderProgress");
        purchaseOrderProgress.setCaption("progress");
        purchaseOrderProgress.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderProgress.setInputProperties("");
        purchaseOrderProgress.getOptions().add(new String[]{"1", "NOT ENOUGH"});
        purchaseOrderProgress.getOptions().add(new String[]{"2", " ENOUGH"});
        getFields().add(purchaseOrderProgress);

        purchaseOrderDescription = new Field();
        purchaseOrderDescription.setName("purchaseOrderDescription");
        purchaseOrderDescription.setCaption("description");
        purchaseOrderDescription.setListProperties(" width=\"60%\"");
        purchaseOrderDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        purchaseOrderDescription.setInputType(Field.INPUT_TEXT_AREA);
        purchaseOrderDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(purchaseOrderDescription);

        purchaseOrderTimestamp = new Field();
        purchaseOrderTimestamp.setName("purchaseOrderTimestamp");
        purchaseOrderTimestamp.setCaption("timestamp");
        purchaseOrderTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        purchaseOrderTimestamp.setInputProperties(" size=\"12\"");
        getFields().add(purchaseOrderTimestamp);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(purchaseOrderDate);
        getFieldsAdd().add(purchaseOrderNumber);
        getFieldsAdd().add(purchaseOrderSupplierId);
        getFieldsAdd().add(purchaseOrderDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(purchaseOrderDate);
        getFieldsEdit().add(purchaseOrderNumber);
        getFieldsEdit().add(purchaseOrderSupplierId);
        getFieldsEdit().add(purchaseOrderDescription);

        getFieldsList().clear();
        getFieldsList().add(purchaseOrderNumber);
        getFieldsList().add(purchaseOrderDate);
        getFieldsList().add(purchaseOrderSupplierId);
        getFieldsList().add(purchaseOrderTotalQuantity);
        getFieldsList().add(purchaseOrderReceived);
        getFieldsList().add(purchaseOrderTotal);
        getFieldsList().add(purchaseOrderReturQuantity);
        getFieldsList().add(purchaseOrderReturTotal);
//        getFieldsList().add(purchaseOrderProgress);
        getFieldsList().add(purchaseOrderStatus);
        getFieldsList().add(purchaseOrderDescription);

        getFieldsView().clear();
        getFieldsView().add(purchaseOrderDate);
        getFieldsView().add(purchaseOrderNumber);
        getFieldsView().add(purchaseOrderSupplierId);
        getFieldsView().add(purchaseOrderTotalQuantity);
        getFieldsView().add(purchaseOrderReceived);
        getFieldsView().add(purchaseOrderTotal);
        getFieldsView().add(purchaseOrderPaid);
        getFieldsView().add(purchaseOrderKeel);
        getFieldsView().add(purchaseOrderReturQuantity);
        getFieldsView().add(purchaseOrderReturTotal);
        getFieldsView().add(purchaseOrderProgress);
        getFieldsView().add(purchaseOrderDescription);
        getFieldsView().add(purchaseOrderUserId);
        getFieldsView().add(purchaseOrderUnitId);
        getFieldsView().add(purchaseOrderTimestamp);

        setExportList(getClass().getResourceAsStream("PurchaseOrderList.jasper"));
        setExport(getClass().getResourceAsStream("PurchaseOrder.jasper"));
        setController(new PurchaseOrder.PurchaseOrderController(this));
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        purchaseOrderDate.setFormater(DateFormatter.getInstanceDate(this));
        purchaseOrderTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        purchaseOrderNumber.setDefaultValue(generate());
    }

    @Override
    public String validate(Object data) {
        HttpSession session = getRequest().getSession();
        List<PosTransactionPurchaseOrderDetail> detail = (List) session.getAttribute("transactions");
        for (PosTransactionPurchaseOrderDetail receiptDetail : detail) {
            if (receiptDetail.getPurchaseOrderDetailPrice() == null) {
                return Dictionary.getValue(this, "Pricing details are still there is an empty");
            }
        }
        return null;
    }

    class PurchaseOrderController extends Controller {

        public PurchaseOrderController(Page page) {
            super(page);
            setOrder(purchaseOrderTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List detail) {
            PosTransactionPurchaseOrder purchaseOrder = (PosTransactionPurchaseOrder) data;
            purchaseOrder.setPurchaseOrderNumber(generate());
            purchaseOrder.setPurchaseOrderUnitId(getCurrentUnit());
            purchaseOrder.setPurchaseOrderUserId(getCurrentUser());
            purchaseOrder.setPurchaseOrderTimestamp(Utility.getTimestamp());
            purchaseOrder.setPurchaseOrderStatus("1");
            purchaseOrder.setPurchaseOrderProgress("1");
            purchaseOrder.setPurchaseOrderKeel("1");
            purchaseOrder.setPurchaseOrderReceived(0);
            purchaseOrder.setPurchaseOrderReturQuantity(0);
            purchaseOrder.setPurchaseOrderReturTotal(BigDecimal.ZERO);
            purchaseOrder.setPurchaseOrderReceived(0);
            int totalQuantity=0;
            BigDecimal total = BigDecimal.ZERO;
            
            for (int i=0; i<detail.size();i++){
                    List<PosTransactionPurchaseOrderDetail> poDetails = detail;
                    totalQuantity = totalQuantity+poDetails.get(i).getPurchaseOrderDetailQuantity();
                    System.out.println("order quantity " + i + " = "+ totalQuantity);
                    total = total.add(poDetails.get(i).getPurchaseOrderDetailPrice().multiply(new BigDecimal(poDetails.get(i).getPurchaseOrderDetailQuantity())));
                    poDetails.get(i).setPurchaseOrderDetailSent(0);
                    poDetails.get(i).setPurchaseOrderDetailUnsent(poDetails.get(i).getPurchaseOrderDetailQuantity());
            }
            
            purchaseOrder.setPurchaseOrderUnreceived(totalQuantity);
            purchaseOrder.setPurchaseOrderTotalQuantity(totalQuantity);
            purchaseOrder.setPurchaseOrderTotal(total);

//            }
        }
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionPurchaseOrder purchaseOrder = (PosTransactionPurchaseOrder) getEntityManager().createQuery("SELECT t FROM PosTransactionPurchaseOrder t WHERE t.purchaseOrderNumber LIKE '%/" + unitCode + "/PUR/%/" + year + "' ORDER BY t.purchaseOrderTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(purchaseOrder.getPurchaseOrderNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/PUR/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/PUR/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Purchase Order"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}